// myFileEncoder.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "myFileEncoder.h"
#include "shlwapi.h"
#include <time.h>
void DoSomething(int x)
{
	int i=x;
	while(!i)
	{
		for(int j=0;j<1000;j+=3)
			i+=j;
		if(i > 10000)break;
		for(int j=0;j<1000;j+=2)
			i-=j;
	}
	printf("%d\n",i);
}
int _tmain(int argc, _TCHAR* argv[])
{
	if(argc>2)
	{
		errno_t retVal;
		clock_t startclock=clock(),endclock;
		retVal=EncodeFile(argv[1],argv[2]);
		endclock=clock();
		printf("time elapsed: %f second\n",1.0*(endclock-startclock)/CLOCKS_PER_SEC);
	}
	DoSomething(0);
	return 0;
}

errno_t EncodeFile(_TCHAR * source,_TCHAR * destine)
{
	TCHAR conf[MAX_PATH];
	DWORD dwRetVal=0;
	HANDLE hFileWrite=NULL;
	HANDLE hFileRead=NULL;
	dwRetVal=GetModuleFileName(NULL,conf,MAX_PATH);
	PathRemoveFileSpec(conf);
	if(_tcslen(conf)+_tcslen(CONFIG_FILE)>=MAX_PATH)
	{
		return ERROR_BUFFER_TOO_SMALL;
	}
	_tcscat(conf,CONFIG_FILE);

	hFileRead=CreateFile(source,GENERIC_READ,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if(NULL==hFileRead || INVALID_HANDLE_VALUE ==hFileRead)
	{
		return ERROR_CANNOT_OPEN_SRC_FILE;
	}
	hFileWrite=CreateFile(destine,GENERIC_WRITE,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
	if(NULL==hFileWrite || INVALID_HANDLE_VALUE==hFileWrite)
	{
		CloseHandle(hFileWrite);
		return ERROR_CANNOT_OPEN_DST_FILE;
	}
	BYTE transform_table[256]={0};
	for(int i=0;i<256;i++)
	{
		TCHAR key[10];
		UINT value;
		_itot(i,key,10);
		value=GetPrivateProfileInt(SECTION_NAME,key,0,conf);
		transform_table[i]=(BYTE)value;
	}//built table
	BYTE *buffer=new BYTE[BUFFER_SIZE];
	DWORD bytes_read,bytes_writen;
	while( 1 )
	{
		ReadFile(hFileRead,buffer,BUFFER_SIZE,&bytes_read,NULL);
		if(bytes_read==0)break;
		for(DWORD i=0;i<bytes_read;i++)
		{
			buffer[i]=transform_table[buffer[i]];
		}
		WriteFile(hFileWrite,buffer,bytes_read,&bytes_writen,NULL);
	}
	CloseHandle(hFileRead);
	CloseHandle(hFileWrite);
	return EXIT_NORMALLY;
}